package com.xiyu.service.repository.medicine;

import com.xiyu.service.model.elder.info.ElderInfoFetcher;
import com.xiyu.service.model.medicine.HealthMedicineFetcher;
import com.xiyu.service.model.medicine.HealthMedicineStockFetcher;
import com.xiyu.service.vo.health.medicineStock.MedicineStockPageQueryInput;
import com.xiyu.service.model.medicine.HealthMedicineStock;
import com.xiyu.service.model.medicine.HealthMedicineStockTable;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;

import java.util.Optional;

public interface HealthMedicineStockRepository extends JRepository<HealthMedicineStock, Long> {
    HealthMedicineStockTable healthMedicineStockTable = HealthMedicineStockTable.$;

    default Page<HealthMedicineStock> pageQuery(MedicineStockPageQueryInput inputVO){
        return sql().createQuery(healthMedicineStockTable)
                        .whereIf(StringUtils.hasText(inputVO.getName()), () -> healthMedicineStockTable.elder().name().like(inputVO.getName()))
                        .whereIf(inputVO.getStockNumberBegin() != null,()-> healthMedicineStockTable.stockNumber().ge(inputVO.getStockNumberBegin()))
                        .whereIf(inputVO.getStockNumberEnd() != null, ()-> healthMedicineStockTable.stockNumber().le(inputVO.getStockNumberEnd()))
                        .orderBy(healthMedicineStockTable.id().desc())
                        .select(healthMedicineStockTable.fetch(HealthMedicineStockFetcher.$.allTableFields()
                                .medicine(HealthMedicineFetcher.$.allTableFields())
                                .elder(ElderInfoFetcher.$.allTableFields())))
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    Optional<HealthMedicineStock> findFirstByElderIdAndMedicineId(Long elderId, Long medicineId);


}